package com.lmxdawn.api.dnf.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lmxdawn.api.admin.entity.Jade;
import com.lmxdawn.api.admin.entity.Md;
import com.lmxdawn.api.admin.entity.Training;
import com.lmxdawn.api.admin.entity.auth.AuthAdmin;
import com.lmxdawn.api.admin.service.IJadeService;
import com.lmxdawn.api.admin.service.IMdService;
import com.lmxdawn.api.admin.service.auth.AuthAdminService;
import com.lmxdawn.api.admin.service.impl.TrainingServiceImpl;
import com.lmxdawn.api.common.res.BaseResponse;
import com.lmxdawn.api.common.session.SessionContextHolder;
import com.lmxdawn.api.common.session.SessionHelper;
import com.lmxdawn.api.common.session.TokenHelper;
import com.lmxdawn.api.common.session.UserSession;
import com.lmxdawn.api.common.util.IdWorker;
import com.lmxdawn.api.common.util.ResultVOUtils;
import com.lmxdawn.api.dnf.annotation.LoginIgnore;
import com.lmxdawn.api.dnf.dto.*;
import com.lmxdawn.api.admin.entity.GoldCoin;
import com.lmxdawn.api.dnf.entity.*;
import com.lmxdawn.api.dnf.service.IChargeConfigService;
import com.lmxdawn.api.dnf.service.IExtraApplyService;
import com.lmxdawn.api.dnf.service.IRealnameService;
import com.lmxdawn.api.admin.service.impl.GoldCoinServiceImpl;
import com.lmxdawn.api.dnf.service.OrderService;
import com.lmxdawn.api.dnf.service.WxPayService;
import com.lmxdawn.api.dnf.service.impl.UserBillServiceImpl;
import com.lmxdawn.api.dnf.service.impl.WithdrawAccountServiceImpl;
import com.lmxdawn.api.im.service.ImUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;
import org.jim.core.packets.ChatBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.jim.core.packets.Command.COMMAND_CHAT_REQ;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author huangyubin
 * @since 2024-07-03
 */
@RestController
@RequestMapping("/web/dnf/mall")
@Slf4j
public class MallController {

    @Resource
    WxPayService wxPayService;

    @Resource
    IRealnameService realnameService;
    @Value("${game.servers}")
    String gameServer;
    @Autowired
    private GoldCoinServiceImpl goldCoinServiceImpl;
    @Autowired
    private IMdService mdService;
    @Autowired
    private IJadeService jadeService;
    @Resource
    private AuthAdminService authAdminService;
    @Resource
    private OrderService orderService;
    @Resource
    private IdWorker idWorker;
    @Resource
    private  IExtraApplyService extraApplyService;
    @Resource
    private  IChargeConfigService chargeConfigService;

    @Resource
    WxpayConfig wxConfig;
    private static final String UPLOAD_DIR = "/upload";
    private static final String DOMAIN = "http://www.5808d.com/img/";
    @Autowired
    private UserBillServiceImpl userBillServiceImpl;
    @Autowired
    private WithdrawAccountServiceImpl withdrawAccountServiceImpl;
    @Autowired
    private TrainingServiceImpl trainingServiceImpl;

    @PostMapping("/upload")
    public BaseResponse sale(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return ResultVOUtils.error(500, "请选择要上传的文件");
        }

        try {
            // 创建上传目录
            String date = DateUtil.format(DateUtil.date(), "yyyyMMdd");
            String baseUrl = UPLOAD_DIR+ File.separator +date;
            File dir = new File(baseUrl);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            // 保存文件
            long l = idWorker.nextId();
            File destinationFile = new File(dir, l + "."
                    + FileUtil.getSuffix(file.getOriginalFilename()));
            file.transferTo(destinationFile);
            return ResultVOUtils.success(DOMAIN+date+"/"+destinationFile.getName());
        } catch (IOException e) {
            return ResultVOUtils.error(500, "文件上传失败: " + e.getMessage());
        }
    }


    @PostMapping("/sale")
    public BaseResponse sale(@RequestBody CommonReq<SaleReq> req, HttpServletRequest request) {
        String tokenValue = TokenHelper.getTokenValue(request);
        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
        val saleReq = req.getContent();
        switch (saleReq.getTab()) {
            case "jade":
                return ResultVOUtils.success(jadeService.doSale(req.getContent(), userSession.getId()));
            case "md":
                return ResultVOUtils.success(mdService.doSale(req.getContent(), userSession.getId()));
            default:
                return ResultVOUtils.success(goldCoinServiceImpl.doSale(req.getContent(), userSession.getId()));
        }
    }

//    @PostMapping("/order/send")
//    public BaseResponse sendOrder(@RequestBody CommonReq<Order> req, HttpServletRequest request) {
//        String tokenValue = TokenHelper.getTokenValue(request);
//        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
//        return ResultVOUtils.success(orderService.sendOrderByUser(req.getContent(), userSession));
//
//    }
    @GetMapping("/wallet/get")
    public BaseResponse wallet(HttpServletRequest request) {
        String tokenValue = TokenHelper.getTokenValue(request);
        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
        return ResultVOUtils.success(authAdminService.queryBalance(userSession));
    }

    @GetMapping("/getOrderInfo")
    public BaseResponse getOrderInfo(HttpServletRequest request) {
        String tokenValue = TokenHelper.getTokenValue(request);
        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
        return ResultVOUtils.success(orderService.getOrderInfo(userSession.getId()));
    }

    @PostMapping("/wallet/extract")
    public BaseResponse walletExtract(@RequestBody CommonReq<ExtractReq> req, HttpServletRequest request) throws AlipayApiException {
        String tokenValue = TokenHelper.getTokenValue(request);
        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
        var b = authAdminService.extractWallet(userSession, req.getContent());
        return b ? ResultVOUtils.success() : ResultVOUtils.error(-1, "提现失败，请联系客服");
    }

    /**
     * 获取列表
     * todo 移动端用户id获取
     */
    @PostMapping("/servers")
    public BaseResponse servers(@RequestBody CommonReq<RealnameReq> req, HttpServletRequest request) {
        String[] serverList = gameServer.split(",");
        return ResultVOUtils.success(serverList);

    }

    @PostMapping("/sale/on")
    public BaseResponse saleOn(HttpServletRequest request, @RequestBody CommonReq<SaleReq> req) {
        val saleReq = req.getContent();
        switch (saleReq.getTab()) {
            case "jade":
                jadeService.lambdaUpdate()
                        .eq(Jade::getId, req.getContent().getId())
                        .set(Jade::getCreateTime, DateUtil.date())
                        .set(Jade::getStatus, 1).update();
                return ResultVOUtils.success();
            case "md":
                mdService.lambdaUpdate()
                        .eq(Md::getId, req.getContent().getId())
                        .set(Md::getCreateTime, DateUtil.date())
                        .set(Md::getStatus, 1).update();
                return ResultVOUtils.success();
            default:
                goldCoinServiceImpl.lambdaUpdate()
                        .eq(GoldCoin::getId, req.getContent().getId())
                        .set(GoldCoin::getCreateTime, DateUtil.date())
                        .set(GoldCoin::getStatus, 1).update();
                return ResultVOUtils.success();
        }
    }

    @PostMapping("/sale/off")
    public BaseResponse saleOff(@RequestBody CommonReq<SaleReq> req) {
        val saleReq = req.getContent();
        switch (saleReq.getTab()) {
            case "jade":
                jadeService.lambdaUpdate()
                        .eq(Jade::getId, req.getContent().getId())
                        .set(Jade::getCreateTime, DateUtil.date())
                        .set(Jade::getStatus, 0).update();
                return ResultVOUtils.success();
            case "md":
                mdService.lambdaUpdate()
                        .eq(Md::getId, req.getContent().getId())
                        .set(Md::getCreateTime, DateUtil.date())
                        .set(Md::getStatus, 0).update();
                return ResultVOUtils.success();
            default:
                goldCoinServiceImpl.lambdaUpdate()
                        .eq(GoldCoin::getId, req.getContent().getId())
                        .set(GoldCoin::getCreateTime, DateUtil.date())
                        .set(GoldCoin::getStatus, 0).update();
                return ResultVOUtils.success();
        }

    }

    @PostMapping("/sale/remove")
    public BaseResponse saleRemove(@RequestBody CommonReq<SaleReq> req) {

        val saleReq = req.getContent();
        switch (saleReq.getTab()) {
            case "jade":
                jadeService.lambdaUpdate()
                        .eq(Jade::getId, req.getContent().getId())
                        .set(Jade::getCreateTime, DateUtil.date())
                        .set(Jade::getStatus, 2).update();
                return ResultVOUtils.success();
            case "md":
                mdService.lambdaUpdate()
                        .eq(Md::getId, req.getContent().getId())
                        .set(Md::getCreateTime, DateUtil.date())
                        .set(Md::getStatus, 2).update();
                return ResultVOUtils.success();
            default:
                goldCoinServiceImpl.lambdaUpdate()
                        .eq(GoldCoin::getId, req.getContent().getId())
                        .set(GoldCoin::getCreateTime, DateUtil.date())
                        .set(GoldCoin::getStatus, 2).update();
                return ResultVOUtils.success();
        }
//        goldCoinServiceImpl.lambdaUpdate()
//                .eq(GoldCoin::getId, obj.getContent().getId()).set(GoldCoin::getStatus, 2).update();
//        return ResultVOUtils.success();
    }


    @PostMapping("/get")
    public BaseResponse get(HttpServletRequest request) {
        RealName one = realnameService.lambdaQuery().eq(RealName::getUserId, SessionContextHolder.getId()).one();
        return ResultVOUtils.success(one);

    }

    @LoginIgnore
    @PostMapping("/rate")
// 获取比率 todo 需要页面来配置比例
    public BaseResponse getRate(HttpServletRequest request, @RequestBody CommonReq<Map> req) {

        String tab = MapUtil.getStr(req.getContent(), "tab");
        switch (tab) {
            case "gold":
            return ResultVOUtils.success(goldCoinServiceImpl.lambdaQuery()
                    .eq(GoldCoin::getType, MapUtil.getInt(req.getContent(), "type"))
//                .eq(GoldCoin::getPlatform,"自营")
                    .list());
            case "md":
                return ResultVOUtils.success(mdService.lambdaQuery()
                        .eq(Md::getType, MapUtil.getInt(req.getContent(), "type"))
//                .eq(GoldCoin::getPlatform,"自营")
                        .list());
            case "jade":
                return ResultVOUtils.success(jadeService.lambdaQuery()
                        .eq(Jade::getType, 0)
//                .eq(GoldCoin::getPlatform,"自营")
                        .list());
            default:
                return ResultVOUtils.success(Lists.newArrayList());
        }
    }


    @PostMapping("/mySaleList")
// 获取比率 todo 需要页面来配置比例
    public BaseResponse mySaleList(HttpServletRequest request,
                                   @RequestBody CommonReq<Map> req) {
        String tokenValue = TokenHelper.getTokenValue(request);
        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
        Map<String, List> res = Maps.newHashMap();
        List<GoldCoin> list = goldCoinServiceImpl.lambdaQuery()
                .eq(GoldCoin::getType, "2")
                .eq(StrUtil.isNotBlank(
                                MapUtil.getStr(req.getContent(), "auction")),
                        GoldCoin::getAuction, MapUtil.getStr(req.getContent(), "auction"))
                .likeRight(StrUtil.isNotBlank(MapUtil.getStr(req.getContent(), "server")), GoldCoin::getGameServer, MapUtil.getStr(req.getContent(), "server"))
//                .eq(GoldCoin::getPlatform,"寄售")
                .orderByDesc(GoldCoin::getCreateTime)
                .ne(GoldCoin::getAmount, 0)
                .ne(GoldCoin::getStatus, 2)
                .eq(GoldCoin::getSaleUser, userSession.getId())
                .list();
        res.put("gold", list);
        List<Md> mdList = mdService.lambdaQuery().eq(Md::getType, "2")
                .eq(StrUtil.isNotBlank(
                                MapUtil.getStr(req.getContent(), "auction")),
                        Md::getAuction, MapUtil.getStr(req.getContent(), "auction"))
                .likeRight(StrUtil.isNotBlank(MapUtil.getStr(req.getContent(), "server")), Md::getGameServer, MapUtil.getStr(req.getContent(), "server"))
//                .eq(GoldCoin::getPlatform,"寄售")
                .orderByDesc(Md::getCreateTime)
                .ne(Md::getAmount, 0)
                .ne(Md::getStatus, 2)
                .eq(Md::getSaleUser, userSession.getId())
                .list();
        res.put("md", mdList);
        List<Jade> jadeList = jadeService.lambdaQuery().eq(Jade::getType, "2")
                .eq(StrUtil.isNotBlank(
                                MapUtil.getStr(req.getContent(), "auction")),
                        Jade::getAuction, MapUtil.getStr(req.getContent(), "auction"))
                .likeRight(StrUtil.isNotBlank(MapUtil.getStr(req.getContent(), "server")), Jade::getGameServer, MapUtil.getStr(req.getContent(), "server"))
//                .eq(GoldCoin::getPlatform,"寄售")
                .orderByDesc(Jade::getCreateTime)
                .ne(Jade::getAmount, 0)
                .ne(Jade::getStatus, 2)
                .eq(Jade::getSaleUser, userSession.getId())
                .list();

        res.put("jade", jadeList);
        return ResultVOUtils.success(res);
    }

    @LoginIgnore
    @PostMapping("/zySaleList")
// 获取比率 todo 需要页面来配置比例
    public BaseResponse zySaleList(HttpServletRequest request,
                                 @RequestBody CommonReq<Map> req) {
        val tab = (String)req.getContent().getOrDefault("tab", "gold");
        switch (tab) {
            case "jade":
                List<Jade> list = jadeService.lambdaQuery()
                        .likeRight(StrUtil.isNotBlank(MapUtil.getStr(req.getContent(), "server")),
                                Jade::getGameServer, MapUtil.getStr(req.getContent(), "server"))
//                .eq(GoldCoin::getPlatform,"寄售")
                        .orderByDesc(Jade::getCreateTime)
                        .ne(Jade::getAmount, 0)
                        .eq(Jade::getType, 1)
                        .eq(Jade::getStatus, 1)
                        .list();
                return ResultVOUtils.success(list);
            case "train":
                return ResultVOUtils.success(trainingServiceImpl.lambdaQuery()
//                .eq(GoldCoin::getPlatform,"寄售")
                        .orderByDesc(Training::getCreateTime)
                        .list());
            default:
                return ResultVOUtils.success(Lists.newArrayList());
        }
    }

    @LoginIgnore
    @PostMapping("/saleList")
// 获取比率 todo 需要页面来配置比例
    public BaseResponse saleList(HttpServletRequest request,
                                 @RequestBody CommonReq<Map> req) {
        val tab = (String)req.getContent().getOrDefault("tab", "gold");
        switch (tab) {
            case "md":
                List<Md> list = mdService.lambdaQuery()
                        .eq(Md::getType, 2)
                        .eq(StrUtil.isNotBlank(
                                        MapUtil.getStr(req.getContent(), "auction")),
                                Md::getAuction, MapUtil.getStr(req.getContent(), "auction"))
                        .likeRight(StrUtil.isNotBlank(MapUtil.getStr(req.getContent(), "server")),
                                Md::getGameServer, MapUtil.getStr(req.getContent(), "server"))
//                .eq(GoldCoin::getPlatform,"寄售")
                        .orderByDesc(Md::getCreateTime)
                        .ne(Md::getAmount, 0)
                        .eq(Md::getStatus, 1)
                        .list();
                return ResultVOUtils.success(list);
            case "jade":
                List<Jade> list2 = jadeService.lambdaQuery()
                        .eq(Jade::getType, 2)
                        .eq(StrUtil.isNotBlank(
                                        MapUtil.getStr(req.getContent(), "auction")),
                                Jade::getAuction, MapUtil.getStr(req.getContent(), "auction"))
                        .likeRight(StrUtil.isNotBlank(MapUtil.getStr(req.getContent(), "server")),
                                Jade::getGameServer, MapUtil.getStr(req.getContent(), "server"))
//                .eq(GoldCoin::getPlatform,"寄售")
                        .orderByDesc(Jade::getCreateTime)
                        .ne(Jade::getAmount, 0)
                        .eq(Jade::getStatus, 1)
                        .list();
                return ResultVOUtils.success(list2);
            default:
                List<GoldCoin> list3 = goldCoinServiceImpl.lambdaQuery()
                        .eq(GoldCoin::getType, 2)
                        .eq(StrUtil.isNotBlank(
                                        MapUtil.getStr(req.getContent(), "auction")),
                                GoldCoin::getAuction, MapUtil.getStr(req.getContent(), "auction"))
                        .likeRight(StrUtil.isNotBlank(MapUtil.getStr(req.getContent(), "server")),
                                GoldCoin::getGameServer, MapUtil.getStr(req.getContent(), "server"))
//                .eq(GoldCoin::getPlatform,"寄售")
                        .orderByDesc(GoldCoin::getCreateTime)
                        .ne(GoldCoin::getAmount, 0)
                        .eq(GoldCoin::getStatus, 1)
                        .list();
                return ResultVOUtils.success(list3);
        }


    }

    @PostMapping("/saveTipsRead")
// 获取比率 todo 需要页面来配置比例
    public BaseResponse saveTipsRead(HttpServletRequest request, @RequestBody CommonReq<Map> req) {

        AuthAdmin byId = authAdminService.findById(SessionContextHolder.getId());
        byId.setTipStatus(1);
        authAdminService.updateAuthAdmin(byId);
        String tokenValue = TokenHelper.getTokenValue(request);
        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
        userSession.setTipRead(true);
        SessionHelper.getSessionStrategy().login(userSession, request, null);
        return ResultVOUtils.success();

    }

    @PostMapping("/joinRoom")
    public BaseResponse joinRoom(String orderNo, HttpServletRequest request) {
        // 获取房间信息
        String tokenValue = TokenHelper.getTokenValue(request);
        UserSession userSession = SessionHelper.getSessionStrategy().getUserSession(tokenValue);
        val list = orderService.joinRoom(orderNo, "app", userSession.getId() + "");
        return ResultVOUtils.success(CollUtil.isEmpty(list)?Lists.newArrayList():list);
    }


    @GetMapping("/wx/bindUser")
    private BaseResponse bindUser() {
        String userId = SessionContextHolder.get().getId();
        AuthAdmin user = authAdminService.findById(userId);
        if (user.getOpenId() != null) {
            return ResultVOUtils.success(MapUtil.of("status", "binded"));
        } else {
            return ResultVOUtils.success(MapUtil.of("qrcode", this.getBindCode(userId)));
        }
    }
    @GetMapping("/user/onlineChange/{status}")
    private BaseResponse onlineChange(@PathVariable String status ) {
        String userId = SessionContextHolder.get().getId();
        authAdminService.updateOnlineStatus(status, userId);
        return ResultVOUtils.success();
    }
    @GetMapping("/wx/unbind")
    private BaseResponse unbind() {
        String userId = SessionContextHolder.get().getId();
        authAdminService.unbind(userId);
        return ResultVOUtils.success();
    }
    /**
     * 删除订单
     *
     * @return
     */
    @PostMapping("/deleteOrder")
    private BaseResponse deleteOrder(@RequestParam String orderId) {
        orderService.deleteOrder(orderId);
        return ResultVOUtils.success();
    }

    /**
     * 确认收货
     *
     * @return
     */
    @PostMapping("/confirmReceive")
    private BaseResponse confirmReceive(@RequestParam String orderId) throws InterruptedException {
        String userId = SessionContextHolder.get().getId();
        orderService.confirmReceive(orderId, userId, 1);
        return ResultVOUtils.success();
    }

    /**
     * 商品发货
     *
     * @return
     */
    @PostMapping("/sendGoods")
    private BaseResponse sendGoods(@RequestParam String orderId) {
        String userId = SessionContextHolder.get().getId();
        orderService.sendOrderByUser(orderId, userId);
        return ResultVOUtils.success();
    }


    @PostMapping("/open")
    private BaseResponse openChat(@RequestParam String orderId) {
        boolean update = orderService.lambdaUpdate()
                .set(Order::getStatus, 3)
                .set(Order::getOpenStatus, 1)
                .eq(Order::getOpenStatus, 0)
                .eq(Order::getId, orderId).update();
        if (update){
            ChatBody resp = ChatBody.newBuilder()
                    .chatType(1)
                    .groupId(orderId)
                    .from("admin")
                    .content("卖家已打开订单准备发货  【务必核实商品名、价格在上下两页中的唯一性，避免因重复导致拍错造成损失】")
                    .setCmd(COMMAND_CHAT_REQ.getNumber())
                    .msgType(0)
                    .setCreateTime(DateUtil.current())
                    .build();
            ImUtil.sendToGroup(orderId, resp);
        }
        return ResultVOUtils.success();
    }
    @PostMapping("/read")
    private BaseResponse readComment(@RequestParam String orderId) {
        String userId = SessionContextHolder.get().getId();

        boolean update = orderService.lambdaUpdate().set(Order::getReadStatus, 1)
                .eq(Order::getReadStatus, 0)
                .eq(Order::getSaleId, userId)
                .eq(Order::getId, orderId).update();
        log.info("readComment===========>{},{}", orderId, update);
        if (update){
            ChatBody resp = ChatBody.newBuilder()
                    .chatType(1)
                    .groupId(orderId)
                    .from(userId)
                    .content("我已阅读并知晓：拍前务必核对上下页唯一且不重复，如购买时有重复商品，造成的损失由我承担！")
                    .setCmd(COMMAND_CHAT_REQ.getNumber())
                    .msgType(0)
                    .setCreateTime(DateUtil.current())
                    .build();
            ImUtil.sendToGroup(orderId, resp);
            this.afterRead(orderId);
        }
        return ResultVOUtils.success();
    }


    private void afterRead(String orderId){
        Order order = orderService.getById(orderId);
        if (order.getStatus() == 3){
            ChatBody resp = ChatBody.newBuilder()
                    .chatType(1)
                    .groupId(orderId)
                    .from("admin")
                    .content("")
                    .setCmd(25)
                    .msgType(0)
                    .setCreateTime(DateUtil.current())
                    .build();
            ImUtil.sendToGroup(orderId, resp);
        }
    }
    @PostMapping("/read2")
    private BaseResponse readComment2(@RequestParam String orderId) {
        String userId = SessionContextHolder.get().getId();

        boolean update = orderService.lambdaUpdate().set(Order::getReadStatus, 1)
                .eq(Order::getReadStatus, 0)
                .eq(Order::getSaleId, userId)
                .eq(Order::getId, orderId).update();
        if (update){
            this.afterRead(orderId);
        }
        return ResultVOUtils.success();
    }


    @PostMapping("/wxpay/jsPay")
    public BaseResponse jsPay(@RequestBody CommonReq<Map> req) throws Exception {
        String userId = SessionContextHolder.get().getId();
        WxJsapiPrepayResp res = wxPayService.jsPay(userId, req.getContent());
        return ResultVOUtils.success(res);
    }


    @PostMapping("/fetchMessage")
    public BaseResponse fetchMessage(String roomId, Integer page) {
        String userId = SessionContextHolder.get().getId();
        return ResultVOUtils.success(orderService.fetchMessage(roomId, userId, page, 10));
    }


    @GetMapping("/billPage")
    public BaseResponse page(@RequestParam Long page) {
        String userId = SessionContextHolder.get().getId();

        return ResultVOUtils.success(
                userBillServiceImpl.page(Page.of(page, 10),
                        Wrappers.<UserBill>lambdaQuery()
                                .eq(UserBill::getUserId, userId)
                                .orderByDesc(UserBill::getCreateTime)
                ));
    }
    /***
     * 根据ID查询数据
     * @param id
     * @return
     */
    @GetMapping("/extraPage")
    public BaseResponse<Page<ExtraApply>> extraPage(@RequestParam Long page,
                                             HttpServletRequest request,
                                             @RequestParam(value = "status", required = false) String status) {
        String userId = SessionContextHolder.get().getId();
        Page<ExtraApply>  pageObj = new Page<>(page, 10);
        Page<ExtraApply> order = extraApplyService.page(pageObj,
                Wrappers.<ExtraApply>lambdaQuery()
                        .eq(ExtraApply::getUserId, userId)
                        .orderByDesc(ExtraApply::getCreateTime)
        );
        List<ExtraApply> records = order.getRecords();
        if (CollUtil.isEmpty(records)){
            return ResultVOUtils.success(pageObj);
        }
        Set<String> account = records.stream().map(ExtraApply::getAccount).collect(Collectors.toSet());
        List<WithdrawAccount> accounts = withdrawAccountServiceImpl.lambdaQuery().in(WithdrawAccount::getId, account).list();
        Map<String, WithdrawAccount> accountMap = accounts.stream().collect(Collectors.toMap(w->w.getId().toString(), Function.identity()));
        for (ExtraApply record : records) {
            WithdrawAccount withdrawAccount = accountMap.get(record.getAccount());
            if (withdrawAccount == null){
                continue;
            }
            record.setAccount(withdrawAccount.getAccount());
            record.setAccountType(StrUtil.equals("1", withdrawAccount.getAccountType()) ? "支付宝": "微信");
        }
        return ResultVOUtils.success(order);
    }




    /***
     * 根据ID查询数据
     * @param id
     * @return
     */
    @GetMapping("/chargeConfig")
    public BaseResponse<Map<String,String>> chargeConfig( ) {
        List<ChargeConfig> list = chargeConfigService.list();
        return ResultVOUtils.success(list.stream().collect(Collectors.toMap(ChargeConfig::getType,ChargeConfig::getCharge )));
    }

    public String getAccessToken() {
        String appID = wxConfig.getAppID();
        String appSecret = wxConfig.getAppSecret();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
        String resp = HttpUtil.get(String.format(url, appID, appSecret));
        JSONObject jsonObject = JSONObject.parseObject(resp);
        String access_token = jsonObject.getString("access_token");
        if (StrUtil.isEmpty(access_token)) {
            throw new RuntimeException("获取token失败 ");
        }
        return access_token;
    }

    public String getBindCode(String userId) {
        String accessToken = this.getAccessToken();
        String url = String.format("https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s", accessToken);
        String param = "bind" + "-" + userId;
        String params = "{\"expire_seconds\": 604800, \"action_name\": \"QR_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"" + param + "\"}}}";
        String resp = HttpUtil.post(url, params);
        JSONObject jsonObject = JSONObject.parseObject(resp);
        String ticket = jsonObject.getString("ticket");
        return String.format("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s", ticket);
    }
}
